package cn.kent.netty.base.eventLoop;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * 客户端
 */
@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture future = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
//                .sync()
//                .channel();

        /*
        // 2.1 使用sync方法同步处理结果
        channel.sync(); // 阻塞住当前线程，直到nio线程连接建立完毕
        Channel channel = future.channel();
        log.debug("{}", channel);
        channel.writeAndFlush("hello, world!"); // 写入通道并立即发送
        */

        // 2.2 使用addListener(回调对象) 方法异步处理结果
        future.addListener(new ChannelFutureListener() {
            @Override
            // 在nio连接建立好后，会调用 operationComplete
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                log.debug("{}", channel);
                channel.writeAndFlush("hello, world!");
            }
        });

    }
}
